<template>
	<view class="page">
		<view class="mpopup">
			<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">
				<view @click="openSelector">
					<mpopupHeaderRadioItem label="申请人名称" :value="selectedRow.operatorName || '[修改]'" height="60px">

					</mpopupHeaderRadioItem>
					<mpopupHeaderRadioItem label="受理号" :value="selectedRow.acceptNumber || '[修改]'" height="60px" />
					<mpopupHeaderRadioItem label="事项" :value="currentorderTypeItem" height="60px" />
					<mpopupHeaderRadioItem label="类别" :value="currentBidTypeText" height="60px" />
					<mpopupHeaderRadioItem label="现场核查日期" :value="selectedRow.deliveryReceiptTime || '[修改]'"
						height="60px" />
					<mpopupHeaderRadioItem label="现场核查人员" :value="selectedRow.checkStaffName || '[修改]'" height="60px" />

				</view>
				<mpopupHeaderRadioItem label="材料审查情况" :custom-class="'custom-align'"
					:custom-style="{ padding: '20rpx' }">
					<input class="centered-input" v-model="selectedRow.reviewStatus" placeholder="请输入材料审查情况" />
				</mpopupHeaderRadioItem>

				<mpopupHeaderRadioItem label="现场核查情况" :custom-class="'custom-align'"
					:custom-style="{ padding: '20rpx' }">
					
						<checkResultTable :table-data="checkResults" :columns="customColumns" @row-click="handleRowClick"
							custom-class="my-custom-table" />
					
					
				</mpopupHeaderRadioItem>

				<mpopupHeaderRadioItem label="综合评审意见" :custom-class="'custom-align'" :show-bottom-border="true"
					:custom-style="{ padding: '20rpx' }">
					<input class="centered-input" v-model="selectedRow.approverOpinion" placeholder="请输入综合评审意见" />
				</mpopupHeaderRadioItem>

			</uni-card>

			<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">

				<!-- 签名区块组件 -->
				<view class="signature-container">
					<SignatureBlock label="经办人签名" :sign-image.sync="selectedRow.checkPersonnelSignOne"
						:date.sync="selectedRow.checkSignDateOne" @open-date-picker="openDatePicker('checkSignDate')" />


					<SignatureBlock label="复核人签名" :sign-image.sync="selectedRow.centerPersonSign"
						:date.sync="selectedRow.centerPersonDate" @open-date-picker="openDatePicker('checkSignDate')" />

					<SignatureBlock label="中心负责人签名" :sign-image.sync="selectedRow.approverPersonSign"
						:date.sync="selectedRow.approverPersonDate"
						@open-date-picker="openDatePicker('checkSignDate')" />


					<!-- 虚线容器 -->
					<view class="dashed-box2">
						<!-- 标题行 -->
						<view class="title-row2">
							<text class="title">珠海市食品药品（医疗器械）审评认证中心（盖章）</text>
							<view class="edit-btn" @click="handleSign(item.type)">
								<evan-checkbox v-model="checked">是否启用电子签章功能</evan-checkbox>

							</view>

						</view>

						<view class="dashed-box3">
							<text style="font-size: 20rpx;font-weight: bold;">+点此签章（部门公章）</text>
						</view>
					</view>


		<view v-if="editStatus!='FALSE'" class="button-container">
			<view class="button-save">
				<button style="flex: 1;" type="primary" @click="submitForm('1')">保存并提交技术评审报告</button>
			</view>
			<view class="button-save">
				<button style="flex: 1;" type="primary" @click="submitForm('0')">暂存</button>
			</view>
		</view>
					
				</view>
			</uni-card>
		</view>



		<!-- 选择器组件

		<enterprise-selector ref="selector" :multiple="true" :initial-selected="selectedList" @confirm="handleConfirm"
			@close="handleClose" />
			 -->
		<EnterpriseSelector tableType="2" :query="{orderType: '2', auditStatus: '1' ,orderCategory: '15'}" type="radio"
			ref="selector" :multiple="false" @confirm="handleConfirm" @close="handleClose" />


		<!-- 添加日期选择弹窗 -->
		<uni-popup ref="datePopup" type="dialog">
			<uni-popup-dialog mode="base" title="选择日期" @confirm="handleDialogConfirm" @close="handleDialogClose">
				<uni-datetime-picker type="date" @change="handleDateChange" />
			</uni-popup-dialog>
		</uni-popup>
	</view>


</template>

<script>
	import signInput from "@/components/am-sign-input/am-sign-input.vue"
	import mpopupHeaderItem from "@/components/mpopup-header-item.vue"
	import mpopupHeaderRadioItem from "@/components/mpopup-header-radio-item.vue"
	import SignatureBlock from '@/components/signature/signature.vue'
	import EnterpriseSelector from "@/components/dialog/enterprise-dialog.vue"
	import checkResultTable from "./components/CheckResultTable.vue"
	import {
		workOrderInfo,
		getScoreCheckInfo,
		foodProductionAdd,
		foodProductionInfo,
		foodProductionUpdate,
		getMedicalDict
	} from '@/api/order'
	export default {
		name: "xlh-table",
		components: {
			signInput,
			mpopupHeaderRadioItem,
			mpopupHeaderItem, // 需先导入组件
			SignatureBlock,
			EnterpriseSelector,
			checkResultTable
		},
		filters: {
			resultFilter(value) {
				const map = {
					'1': '符合',
					'2': '不符合'
				}
				return map[value] || '未检查'
			}
		},
		computed: {
			
			  currentBidTypeText() {
			    // 优先取 matter，没有则取 latter
			    const value = this.selectedRow.bidType || this.selectedRow.businessFormat;
			    const item = this.bidTypeItem.find(item => item.value === value);
			    return item ? item.text : '[修改]';
			  },
			  currentorderTypeItem() {
			    // 优先取 matter，没有则取 latter
			    const value = this.selectedRow.orderType || this.selectedRow.matter;
			    const item = this.orderTypeItem.find(item => item.value === value);
			    return item ? item.text : '[修改]';
			  }
		
		},
		onLoad(options) {
			const workOrderId = decodeURIComponent(options.workOrderId);
			if (options.editStatus != null) {
				const editStatus = decodeURIComponent(options.editStatus);
				this.editStatus = editStatus;
				this.foodProductionInfo(workOrderId);

			} else {
				if (options.orderData) {
					const orderData = JSON.parse(decodeURIComponent(options.orderData));
				}
			}
			this.workOrderId = workOrderId;
			this.selectedRow.workOrderId = workOrderId
			this.getMedicalDict('order_type')
			this.getMedicalDict('bid_type')
		},

		data() {
			return {
				searchText: '',
				workOrderId: '',
				action: "https://8954wg323mw0.vicp.fun/app/upload/imageFile", //上传服务器的地址
				currentDate: '',
				tableData: [],
				// 分页控制参数
				pageSize: 10, // 保持固定值
				total: 0, // 总数据量
				currentPage: 1, // 当前页码（建议更名更清晰）
				selectedRow: {
					workOrderId: '',
					checkPersonnelSignOne: '',
					checkSignDateOne: '',
					foodPersonSign: '',
					centerPersonSign: '',
					reviewOpinions: '',
					checkCount: 0, // 替换检查项目数
					checkNoConform: 0,
					operatorName: '',
					address: '',
					acceptNumber: '',
					bidType: '',
					checkOpinion: 0,
					reviewStatus: '',
					auditStatus: 0,

				}, // 存储选中行数据
				checkResults: [
					/*{
						actualScore: "97",
						categoryName: "0101",
						checkResult: "2",
						projectNameScore: "102",
						foodCategory: "0100",
						scoringRate: "95.00%",
						scoreIsZero: "1",
						workOrderId: "260934570592763904"
					}*/
				],
				editStatus: 'ADD',
				auditStatusMap: {
					'0': '未完成',
					'1': '已完成'
				},
				signList: [{
						type: 'handler',
						title: '经办人签名'
					},
					{
						type: 'reviewer',
						title: '复核人签名'
					},
					{
						type: 'director',
						title: '中心负责人签名'
					}
				],

				radio1: 0,
				radio2: 0,
				valueOptions: [],
				valueOptions2: [],
				projectItem: {},
				formatItem: {},
				checkBoxIndex: 0,
				remarkDialog: '',
				bidTypeItem: [],
				orderTypeItem:[]
			}
		},
		methods: {

			// 打开选择器
			openSelector() {
				this.$refs.selector.open()
			},
			handleConfirm(selected) {
				this.selectedRow = selected
				console.log(this.selectedRow.orderType)
				this.getScoreCheckInfo(this.selectedRow.id)
			},
			handleClose() {
				console.log('弹窗已关闭')
			},
			// 获取工单详情
			async foodProductionInfo(orderId) {
				const data = {
					workOrderId: orderId //工单主键
				}
				const res = await foodProductionInfo(data);
				if (res.code === 0) {
					this.selectedRow = res.data;
					console.log(this.selectedRow)
					if(this.selectedRow.verificationSituation!=null){
						this.getScoreCheckInfo(this.selectedRow.verificationSituation)
					}
					
				}
			},

			// 获取查询得分、评分率、结论 副本
			async getScoreCheckInfo(orderId) {

				const data = [orderId]
				console.log(data)
				const res = await getScoreCheckInfo(data);
				if (res.code === 0) {
					this.checkResults = res.data;
				}
			},

			/// 提交方法
			async submitForm(status) {
				try {
					this.selectedRow.workOrderId = this.workOrderId
					if (!this.selectedRow.workOrderId) {
						uni.showToast({
							title: '请选择要提交的报告',
							icon: 'error'
						});
						return;
					}

					// 状态校验前置
					if (this.editStatus === 'FALSE') {
						return uni.showToast({
							title: '当前处于查看状态',
							icon: 'none'
						});
					}
					// 统一处理提交逻辑
					const isEditMode = this.editStatus === 'EDIT';
					const apiMethod = isEditMode ? foodProductionAdd : foodProductionAdd;
					// 构造请求参数（避免污染原始数据）
					const payload = {
						...this.selectedRow,
						auditStatus: status,
					};

					// 显示加载状态
					uni.showLoading({
						title: '提交中...',
						mask: true
					});

					console.log(payload)
					// 执行API调用
					const res = await apiMethod(payload);

					if (res.code !== 0) {
						throw new Error(res.msg || '服务器处理异常');
					}

					// 统一处理成功逻辑
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});

					// 关闭当前页面，跳转到工单页
					this.$closeAndRedirect({
					  url: '/pages/work/history/index'
					});

				} catch (error) {
					// 统一错误处理
					console.error('提交失败:', error);
					uni.showToast({
						title: error.msg || '请求失败，请检查网络',
						icon: 'none',
						duration: 3000
					});
				} finally {
					uni.hideLoading();
				}
			},

			//获取字典值
			async getMedicalDict(type) {
				try {
					const res = await getMedicalDict(type)
					// 增加响应状态判断
					if (res.code === 0) {
						if (type === 'bid_type') { //申办类型
							this.bidTypeItem = res.data.map(item => ({
								text: item.label,
								value: item.value
							}))
						}else if(type==='order_type'){
							this.orderTypeItem = res.data.map(item => ({
								text: item.label,
								value: item.value
							}))
						}
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '获取失败',
						icon: 'none',
						duration: 2000
					})
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	.container-bottom {
		margin-top: 10px;
		display: flex;
		justify-content: center;
		/* 水平居中 */
		align-items: center;
		/* 垂直居中 */
	}


	.page {
		background-color: #e9f1fe;
		padding: 20px;
	}



	.centered-input {
		width: 100%;
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		/* 保持与高度一致 */
		border-radius: 12rpx;
	}

	// 弹窗容器样式
	.custom-popup {
		width: auto !important;
		/* 自适应宽度 */
		min-width: 300px;
		max-width: 80%;
		border-radius: 8px;

		/* 按钮容器 */
		.dialog-buttons {
			display: flex;
			justify-content: flex-end;
			gap: 10px;
			margin-top: 20px;
		}

		/* 取消按钮 */
		.cancel-btn {
			background-color: #f0f0f0 !important;
			color: #666 !important;
		}

		/* 确定按钮 */
		.confirm-btn {
			background-color: #2979ff !important;
			color: white !important;
		}




		// 内容区域适配
		.dialog-container {
			padding: 30px;
			max-height: 80vh; // 控制最大高度
			overflow-y: auto;
			border-radius: 10px;

			.uni-container {
				width: 100%;

				// 表格适配
				uni-table {
					width: 100%;

					// 单元格内容换行
					uni-td,
					uni-th {
						white-space: normal !important;
						word-break: break-word;
						padding: 8px 12px;
					}
				}

				// 分页器适配
				.uni-pagination-box {
					margin-top: 15px;
					padding: 0 10px;
				}
			}
		}
	}

	// 新增响应式处理
	@media (max-width: 768px) {
		.custom-popup {
			width: 90% !important;
			max-width: none;

			.dialog-container {
				padding: 15px;

				uni-table {
					font-size: 14px;

					uni-td,
					uni-th {
						padding: 6px 8px;
					}
				}
			}
		}
	}

	.custom-title {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 10px;
		/* 保持原有下边距 */

	}


	.custom-dateText {
		display: flex;
		margin: 20px;
		justify-content: flex-end;

		/* 子元素居左 */
	}

	.custom-text3 {
		padding-left: 10px;
		color: #0055ff;
		font-size: 16px;

		font-weight: bold;
		padding-right: 10px;

	}

	/* 优化后的样式 */
	.optimized-table {
		font-size: 14px;
		border: 1px solid #ebeef5;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
	}

	.header-cell {
		background-color: #f5f7fa !important;
		color: #303133;
		font-weight: 600;
		padding: 12px 8px;
	}

	.body-cell {
		padding: 10px 8px;
		color: #606266;
		line-height: 1.5;
	}

	.table-row:hover {
		background-color: #fafafa;
	}

	.even-row {
		background-color: #fafafa;
	}

	.odd-row {
		background-color: #ffffff;
	}

	.address-text {
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.status-cell {
		min-width: 80px;
	}

	.pagination-container {
		margin-top: 20px;
		padding: 12px;
		background: #fff;
		border-radius: 8px;
		display: flex;
		justify-content: flex-end;
	}

	/* 移动端适配 */
	@media screen and (max-width: 768px) {
		.optimized-table {
			font-size: 12px;
		}

		.header-cell {
			padding: 8px 4px;
		}

		.body-cell {
			padding: 6px 4px;
		}

		.pagination-container {
			flex-wrap: wrap;
			justify-content: center;
		}
	}

	/* 添加选中行高亮样式 */
	.uni-table-tr.selected-row {
		background-color: #f5f7fa;
	}

	/* 添加行点击效果 */
	.uni-table-tr {
		cursor: pointer;
		transition: background-color 0.3s;
	}

	.uni-table-tr:hover {
		background-color: #fafafa;
	}

	/* 新增搜索框样式 */
	.search-input {
		margin-bottom: 20px;

		/deep/ .uni-easyinput__content {
			border-radius: 15px;
			padding: 0 15px;
		}
	}

	/* 虚线容器 */
	.dashed-box2 {
		width: 100%;
		margin: 24rpx auto;
		padding: 12rpx;
		border: 2rpx dashed #333;
		border-radius: 10rpx;
		background: #fff;
		margin-bottom: 40px;
		position: relative;

		&+.dashed-box {
			margin-top: 28rpx;
		}
	}

	/* 虚线容器 */
	.dashed-box3 {
		width: 100%;
		border: 2rpx dashed #0055ff;
		border-radius: 10rpx;
		background: #e5ecff;
		height: 120px;
		/* 设置为flex布局 */
		display: flex;
		/* 水平居中 */
		justify-content: center;
		/* 垂直居中 */
		align-items: center;
	}

	/* 标题行 */
	.title-row2 {
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		margin-bottom: 68rpx;

		.title {
			font-size: 16rpx;
			color: #333;
			font-weight: 500;

		}

		.edit-btn {

			.btn-text {
				color: #2196F3;
				font-size: 16rpx;
				margin-left: 60px;
				margin-right: 16rpx;
			}


		}
	}
	
	.button-container {
		display: flex;
		background-color: #ffffff;
		width: 100%;
		padding: 10px;
		flex-direction: column;
		/* 垂直排列 */
	
		.button-save {
			margin-bottom: 10px;
		}
	
		.button-child {
			display: flex;
			flex-direction: row;
			/* 垂直排列 */
	
		}
	}
</style>